package ru.spb.osll.myfit.wikiverifier.resulthandler;

import ru.spb.osll.myfit.common.Table;
import ru.spb.osll.myfit.wikiverifier.result.AggregatedVerificationResult;
import ru.spb.osll.myfit.wikiverifier.result.PageVerificationResult;
import ru.spb.osll.myfit.wikiverifier.result.TableVerificationResult;
import ru.spb.osll.myfit.wikiverifier.result.VerificationResultType;

public class ConsoleVerificationResultHandler implements
		PageVerificationResultHandler, AggregatedVerificationResultHandler {

	@Override
	public void handleResult(String directory,
			AggregatedVerificationResult aggregatedRes) {
	}

	@Override
	public void handleResult(String pagePath, PageVerificationResult pageResult) {
		System.out.println(pagePath + " " + pageResult.getResult());
		for (TableVerificationResult tableRes : pageResult.getTableResults()) {
			if (tableRes.getResult() == VerificationResultType.ERROR) {
				printError(tableRes);
			} else if (tableRes.getResult() == VerificationResultType.FAILURE) {
				printSuggestion(tableRes);
			}
		}
	}

	private String tableToString(Table table) {
		if (table == null) {
			return "";
		}

		if (table.isEmpty())
			return "";

		String res = "";

		for (int i = 0; i < table.getData().size(); i++) {
			for (int j = 0; j < table.getData().get(i).size(); j++) {
				res = res + "|";
				res = res + table.getData().get(i).get(j);
			}
			res = res + "|\n";
		}

		return res;
	}

	private void printError(TableVerificationResult tableResult) {
		System.out.println("  Failed to verify test table:");
		System.out.println(tableToString(tableResult.getTable()));
		if (tableResult.getException() != null) {
			System.out.println("  Exception:");
			tableResult.getException().printStackTrace(System.out);
		}
	}

	private void printSuggestion(TableVerificationResult tableResult) {
		System.out.println("  Error in test table:");
		System.out.println(tableToString(tableResult.getTable()));
		if (tableResult.getSuggestion() != null) {
			System.out.println("  Suggestion:");
			System.out.println(tableToString(tableResult.getSuggestion()));
		}
	}

}
